<template>
	<div class="container">
		<Breadcrumb :items="['menu.biz', 'menu.biz.goods']" />
		<a-card :title="$t('menu.biz.goods')">
			<a-space fill direction="vertical">
				<!-- 搜索表单 -->
				<a-form layout="inline" :model="searchForm" @submit="handleSearch">
					<a-form-item field="title" label="商品名称" :hide-label="true">
						<a-input v-model="searchForm.title" placeholder="请输入商品名称" allow-clear />
					</a-form-item>
					<a-form-item field="biz_id" label="所属商家" :hide-label="true">
						<a-select v-model="searchForm.biz_id" placeholder="请选择商家" allow-clear style="width: 200px">
							<a-option v-for="item in bizList" :key="item.id" :value="item.id">{{ item.name }}</a-option>
						</a-select>
					</a-form-item>
					<a-form-item field="status" label="上下架状态" :hide-label="true">
						<a-select v-model="searchForm.status" placeholder="请选择状态" allow-clear style="width: 150px">
							<a-option :value="1">上架</a-option>
							<a-option :value="0">下架</a-option>
						</a-select>
					</a-form-item>
					
					<a-form-item>
						<a-space>
							<a-button type="primary" html-type="submit" shape="round">
								<template #icon><icon-search /></template>
								搜索
							</a-button>
							<a-button shape="round" @click="resetSearch">
								<template #icon><icon-refresh /></template>
								重置
							</a-button>
						</a-space>
					</a-form-item>
				</a-form>

				<a-row :gutter="16">
					<a-col :span="12">
						<a-space fill>
							<a-button type="primary" @click="openModal()" shape="round">
								<template #icon><icon-plus /></template>
								添加商品
							</a-button>
						</a-space>
					</a-col>
				</a-row>

				<a-table :data="renderData" :loading="loading" :bordered="{ cell: true }" :pagination="pagination"
					@page-change="onPageChange" @page-size-change="onPageSizeChange" scroll="{x: '1170'}">
					<template #columns>
						<a-table-column title="ID" data-index="id" :width="80" />
						<a-table-column title="图片" data-index="image_url" :width="90">
							<template #cell="{ record }">
								<a-image :src="record.image_url" :width="60" :height="60" style="border-radius: 6px;" />
							</template>
						</a-table-column>
						<a-table-column title="商品名称" data-index="title">
							<template #cell="{ record }">
								<div><strong>{{record.title}}</strong></div>
							</template>
						</a-table-column>	

						<a-table-column title="所属商家" data-index="biz_name" :width="150" :ellipsis="true"
							:tooltip="true" />
						<a-table-column title="相册数量" data-index="image_total" :width="100">
							<template #cell="{ record }">
								<a-typography-text type="primary" underline @click="openAlbumModal(record)">{{record.image_total}}</a-typography-text>
							</template>
						</a-table-column>
						<a-table-column title="商品价格" data-index="price" :width="100" />
						<a-table-column title="市场价格" data-index="market_price" :width="100" />
						<a-table-column title="已售销量" data-index="sellout_count" :width="100" />
						<a-table-column title="评价数量" data-index="ping_count" :width="100" />

						<a-table-column title="上下架" data-index="status" :width="100">
							<template #cell="{ record }">
								<a-tag 
									:color="record.status === 1 ? 'green' : 'red'" 
									@click="handleToggleStatus(record)"
									style="cursor: pointer;"
								>
									{{ record.status === 1 ? '上架' : '下架' }}
								</a-tag>
							</template>
						</a-table-column>
						<a-table-column title="创建时间" data-index="created_at" :width="180" />
						<a-table-column title="操作" data-index="action" :width="120" fixed="right">
							<template #cell="{ record }">
								<a-space>
									<a-link @click="openModal(record)">编辑</a-link>
									<a-popconfirm position="left" content="确定要删除这个商品吗？" @ok="handleDelete(record.id)">
										<a-link>
											删除
										</a-link>
									</a-popconfirm>
								</a-space>
							</template>
						</a-table-column>
					</template>
				</a-table>
			</a-space>
		</a-card>

		<a-modal v-model:visible="modalVisible" width="850px" :draggable="true" :title="formData.id ? '编辑商品' : '添加商品'"
			@before-ok="handleSubmit" @cancel="closeModal">
			<a-form :model="formData" ref="formRef" layout="vertical">
				<a-row :gutter="16">
					<a-col :span="16">
						<a-form-item field="title" label="商品名称" :rules="[{ required: true }]">
							<a-input v-model="formData.title" placeholder="请输入名称" />
						</a-form-item>
					</a-col>
					<a-col :span="8">
						<a-form-item field="market_price" label="市场价格" :rules="[{ required: true }]">
							<a-input v-model="formData.market_price" placeholder="请输入市场价格" />
						</a-form-item>
					</a-col>
				</a-row>

				<a-form-item label="图片" :rules="[{ required: true }]">
					<a-upload list-type="picture" v-model="formData.image" :custom-request="handleUpload" :limit="1"
						:file-list="fileList" image-preview @before-remove="beforeRemove" />
					<template #extra>
						<div>请保持图片比例为1:1，格式为jpg/png</div>
					</template>
				</a-form-item>

				<a-row :gutter="16">
					<a-col :span="8">
						<a-form-item field="biz_id" label="所属商家" :rules="[{ required: true }]">
							<a-select v-model="formData.biz_id" placeholder="请选择商家">
								<a-option v-for="item in bizList" :key="item.id" :value="item.id">{{ item.name
									}}</a-option>
							</a-select>
						</a-form-item>
					</a-col>
					<a-col :span="8">
						<a-form-item field="price" label="商品价格" :rules="[{ required: true }]">
							<a-input v-model="formData.price" placeholder="请输入价格" />
						</a-form-item>
					</a-col>
					<a-col :span="8">
						<a-form-item field="status" label="上下架" :rules="[{ required: true }]">
							<a-select v-model="formData.status" placeholder="请选择状态">
								<a-option :value="1">上架</a-option>
								<a-option :value="0">下架</a-option>
							</a-select>
						</a-form-item>
					</a-col>
				</a-row>

				<a-form-item field="desc" label="商品描述" :rules="[{ required: true }]">
					<div class="markdown-editor-container">
						<v-md-editor v-model="formData.desc" @upload-image="handleUploadImage" :disabled-menus="[]" height="300px" style="width: 100%;" />
					</div>
				</a-form-item>
			</a-form>
		</a-modal>

		<!-- 相册管理弹窗 -->
		<a-modal v-model:visible="albumModalVisible" width="900px" :draggable="true" title="商品相册管理"
			@cancel="closeAlbumModal">
			<div v-if="currentGoods">
				<a-space direction="vertical" fill size="large">
					<!-- 相册头部信息 -->
					<a-card size="small">
						<a-space>
							<a-image :src="currentGoods.image_url" :width="100" :height="100" fit="cover" />
							<div>
								<a-typography-title :heading="4">
									[{{ currentGoods.id }}]{{ currentGoods.title }}
								</a-typography-title>
							</div>
						</a-space>
					</a-card>

					<!-- 添加图片 -->
					<a-card size="small" title="添加图片">
						<a-space direction="vertical" fill>
							<a-upload list-type="picture-card" :custom-request="handleAlbumUpload" :limit="10"
								:file-list="albumFileList" image-preview @before-remove="beforeAlbumRemove"
								accept="image/*">
								<template #upload-button>
									<a-button type="primary" shape="round">
										<template #icon><icon-plus /></template>
										点击上传图片
									</a-button>
								</template>
							</a-upload>
							<div>支持jpg、png格式，建议尺寸800x800</div>
						</a-space>
					</a-card>

					<!-- 相册列表 -->
					<a-card size="small" title="相册列表">
						<a-row :gutter="24" :loading="albumLoading">
							<a-col :span="12" v-for="item in albumList" :key="item.id">
								<a-space>
									<a-image :src="item.url" :width="80" :height="80"  fit="cover" />
									<div style="flex: 1;">
										<a-input v-model="item.title" placeholder="图片标题" size="small" />
										<div style="margin-top: 8px;">
											<a-space>
												<a-button size="mini" shape="round" @click="updateImageInfo(item)">保存</a-button>
												<a-popconfirm content="确定要删除这张图片吗？" @ok="deleteImage(item.id)">
													<a-button size="mini" shape="round" status="danger">删除</a-button>
												</a-popconfirm>
											</a-space>
										</div>
									</div>
								</a-space>
							</a-col>
						</a-row>
						
					</a-card>
				</a-space>
			</div>
		</a-modal>
	</div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { Message } from '@arco-design/web-vue';
import type { UploadRequest, RequestOption, FileItem } from '@arco-design/web-vue';
import useLoading from '@/hooks/loading';
import { Pagination } from '@/types/global';
import { queryBizGoodsList, submitBizGoodsForm, delBizGoods, toggleBizGoodsStatus, BizGoodsRecord } from '@/api/bizGoods';
import { queryAllBiz, BizRecord } from '@/api/biz';
import { uploadFile } from '@/api/upload';
import {
	queryBizGoodsImages,
	addBizGoodsImage,
	delBizGoodsImage,
	updateBizGoodsImage,
	BizGoodsImageRecord
} from '@/api/bizGoodsImage';
import VMdEditor from '@kangc/v-md-editor';
import '@kangc/v-md-editor/lib/style/base-editor.css';
import githubTheme from '@kangc/v-md-editor/lib/theme/github';
import '@kangc/v-md-editor/lib/theme/style/github.css';
import createEmojiPlugin from '@kangc/v-md-editor/lib/plugins/emoji/index';
import '@kangc/v-md-editor/lib/plugins/emoji/emoji.css';
import createTodoListPlugin from '@kangc/v-md-editor/lib/plugins/todo-list/index';
import '@kangc/v-md-editor/lib/plugins/todo-list/todo-list.css';
import createAlignPlugin from '@kangc/v-md-editor/lib/plugins/align/index';
import createLineNumbertPlugin from '@kangc/v-md-editor/lib/plugins/line-number/index';
import createCopyCodePlugin from '@kangc/v-md-editor/lib/plugins/copy-code/index';
import '@kangc/v-md-editor/lib/plugins/copy-code/copy-code.css';
import createHighlightLinesPlugin from '@kangc/v-md-editor/lib/plugins/highlight-lines/index';
import '@kangc/v-md-editor/lib/plugins/highlight-lines/highlight-lines.css';

// 配置v-md-editor
VMdEditor.use(githubTheme);
VMdEditor.use(createEmojiPlugin());
VMdEditor.use(createTodoListPlugin());
VMdEditor.use(createAlignPlugin());
VMdEditor.use(createLineNumbertPlugin());
VMdEditor.use(createCopyCodePlugin());
VMdEditor.use(createHighlightLinesPlugin());

const { loading, setLoading } = useLoading(true);
const modalVisible = ref(false);
const albumModalVisible = ref(false);
const formRef = ref();
const fileList = ref<FileItem[]>([]);
const albumFileList = ref<FileItem[]>([]);
const albumLoading = ref(false);
const currentGoods = ref<BizGoodsRecord | null>(null);
const albumList = ref<BizGoodsImageRecord[]>([]);

// 搜索表单数据
const searchForm = reactive({
	title: '',
	biz_id: undefined as number | undefined,
	status: undefined as number | undefined,
});

const basePagination = {
	current: 1,
	pageSize: 10,
	total: 0,
};

const pagination = reactive({
	...basePagination,
});

const generateFormData = () => {
	return {
		id: 0,
		title: '',
		biz_id: '',
		image: '',
		price: '',
		market_price: '',
		status: 1,
		desc: ''
	};
};

const formData = ref(generateFormData());

const renderData = ref<BizGoodsRecord[]>([]);

const fetchData = async () => {
	setLoading(true);
	try {
		const { data } = await queryBizGoodsList({
			current: pagination.current,
			pageSize: pagination.pageSize,
			title: searchForm.title || undefined,
			biz_id: searchForm.biz_id,
			status: searchForm.status,
		});
		renderData.value = data.list;
		pagination.total = data.total;
	} catch (err) {
		Message.error('获取商品列表失败');
	} finally {
		setLoading(false);
	}
};

const onPageChange = (current: number) => {
	pagination.current = current;
	fetchData();
};

const onPageSizeChange = (pageSize: number) => {
	pagination.pageSize = pageSize;
	pagination.current = 1;
	fetchData();
};

// 搜索处理
const handleSearch = () => {
	pagination.current = 1;
	fetchData();
};

const bizList = ref<BizRecord[]>([]);
const fetchBizList = async () => {
	const { data } = await queryAllBiz();
	bizList.value = data;
};

const openModal = (record?: BizGoodsRecord) => {
	if (record) {
		formData.value = {
			id: record.id,
			title: record.title,
			biz_id: record.biz_id,
			image: record.image,
			price: record.price,
			market_price: record.market_price,
			status: record.status,
			desc: record.desc
		};

		fileList.value = [{ url: record.image_url }];
	} else {
		formData.value = generateFormData();
	}
	modalVisible.value = true;
};

const closeModal = () => {
	modalVisible.value = false;
	formData.value = generateFormData();
};

// 相册相关方法
const openAlbumModal = async (record: BizGoodsRecord) => {
	currentGoods.value = record;
	albumModalVisible.value = true;
	await fetchAlbumList(record.id);
};

const closeAlbumModal = () => {
	albumModalVisible.value = false;
	currentGoods.value = null;
	albumList.value = [];
	albumFileList.value = [];
};

const fetchAlbumList = async (goodsId: number) => {
	albumLoading.value = true;
	try {
		const { data } = await queryBizGoodsImages({ goods_id: goodsId });
		albumList.value = data;
	} catch (err) {
		Message.error('获取相册列表失败');
	} finally {
		albumLoading.value = false;
	}
};

const handleAlbumUpload = (option: RequestOption): UploadRequest => {
	const { onProgress, onError, onSuccess, fileItem } = option;

	const uploadFormData = new FormData();
	uploadFormData.append('file', (fileItem.file as any));

	uploadFile(uploadFormData).then(async ({ data }) => {
		if (currentGoods.value) {
			try {
				await addBizGoodsImage({
					goods_id: currentGoods.value.id,
					path: data.path,
					title: '',
					sort: albumList.value.length
				});
				Message.success('添加图片成功');
				await fetchAlbumList(currentGoods.value.id);
				albumFileList.value = [];
				onSuccess();
			} catch (err) {
				Message.error('添加图片失败');
				onError();
			}
		}
	}).catch((err) => {
		Message.error('上传失败');
		onError();
	});

	return {
		abort: () => { },
	};
};

const beforeAlbumRemove = async (fileItem: FileItem): Promise<boolean> => {
	return true;
};

const deleteImage = async (imageId: number) => {
	try {
		await delBizGoodsImage(imageId);
		Message.success('删除成功');
		if (currentGoods.value) {
			await fetchAlbumList(currentGoods.value.id);
		}
	} catch (err) {
		Message.error('删除失败');
	}
};

const updateImageInfo = async (image: BizGoodsImageRecord) => {
	try {
		await updateBizGoodsImage({
			id: image.id,
			title: image.title,
			sort: image.sort,
			path: image.path,
			goods_id: image.goods_id
		});
		Message.success('更新成功');
	} catch (err) {
		Message.error('更新失败');
	}
};

const handleUpload = (option: RequestOption): UploadRequest => {
	const { onProgress, onError, onSuccess, fileItem } = option;

	const uploadFormData = new FormData();
	// 使用any类型避免TypeScript错误
	uploadFormData.append('file', (fileItem.file as any));

	uploadFile(uploadFormData).then(({ data }) => {
		formData.value.image = data.url;
		fileList.value = [{ url: data.url } as FileItem];
		Message.success('上传成功');
		onSuccess();
	}).catch((err) => {
		Message.error('上传失败');
		onError();
	});

	return {
		abort: () => { },
	};
};

const beforeRemove = async (fileItem: FileItem): Promise<boolean> => {
	formData.value.image = '';
	fileList.value = [];
	return true;
};

// 富媒体编辑框图片上传方法
const handleUploadImage = async (event: any, insertImage: any) => {
	try {
		// 创建文件输入元素
		const input = document.createElement('input');
		input.type = 'file';
		input.accept = 'image/*';
		
		input.onchange = async (e: any) => {
			const file = e.target.files[0];
			if (!file) {
				Message.warning('请选择要上传的图片');
				return;
			}

			// 检查文件类型
			if (!file.type.startsWith('image/')) {
				Message.error('只能上传图片文件');
				return;
			}

			// 检查文件大小（限制为5MB）
			const maxSize = 5 * 1024 * 1024; // 5MB
			if (file.size > maxSize) {
				Message.error('图片大小不能超过5MB');
				return;
			}

			try {
				const uploadFormData = new FormData();
				uploadFormData.append('file', file);
				
				const { data } = await uploadFile(uploadFormData);
				
				// 插入图片到编辑器
				insertImage({
					url: data.url,
					alt: file.name,
					title: file.name
				});
				
				Message.success('图片上传成功');
			} catch (err) {
				console.error('图片上传失败:', err);
				Message.error('图片上传失败，请重试');
			}
		};
		
		// 触发文件选择
		input.click();
	} catch (err) {
		console.error('图片上传失败:', err);
		Message.error('图片上传失败，请重试');
	}
};

const handleSubmit = async (done: (closed: boolean) => void) => {
	setLoading(true);
	try {
		const res = await submitBizGoodsForm(formData.value);
		Message.success('操作成功');
		closeModal();
		fetchData();
		done(true);
	} catch (err) {
		Message.error('操作失败');
		done(false);
	}
};

const handleDelete = async (id: number) => {
	setLoading(true);
	try {
		await delBizGoods(id);
		Message.success('操作成功');
		fetchData();
	} catch (err) {
		Message.error('删除失败');
	} finally {
		setLoading(false);
	}
};

const handleToggleStatus = async (record: BizGoodsRecord) => {
	try {
		const { data,msg } = await toggleBizGoodsStatus(record.id);
		Message.success(msg);
		// 更新本地数据状态
		record.status = data.status;
	} catch (err) {
		Message.error('状态切换失败');
	}
};

const resetSearch = () => {
	searchForm.title = '';
	searchForm.biz_id = undefined;
	searchForm.status = undefined;
	pagination.current = 1;
	fetchData();
};

onMounted(() => {
	fetchBizList();
	fetchData();
});
</script>

<style scoped lang="less">
.container {
	padding: 0 20px 20px 20px;
}

.markdown-editor-container {
	border: 1px solid #d9d9d9;
	border-radius: 6px;
	overflow: hidden;
	width: 100%;
}

.markdown-editor-container :deep(.v-md-editor) {
	border: none;
	width: 100%;
}

.markdown-editor-container :deep(.v-md-editor__toolbar) {
	border-bottom: 1px solid #f0f0f0;
}

.markdown-editor-container :deep(.v-md-editor__editor-wrapper) {
	border: none;
	width: 100%;
}
</style>

<script lang="ts">
export default {
	name: 'BizGoods',
};
</script>